#!/bin/sh

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

OPTNOW=" --now --retries=10 --timeout=1 --script=/etc/udhcp.script"
OPTBGND=" --background -S --retries=10 --timeout=6 --script=/etc/udhcp.script"
CFGGILE="/etc/opendomo/network.conf"
start(){
	if ! /sbin/ifconfig eth0 up 2>/dev/null >/dev/null
	then
		echo -n "Network unavailable: eth0 missing!"
		exit 1
	fi
	/sbin/route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0  2>/dev/null > /dev/null
	/sbin/route add -net 169.254.0.0 netmask 255.255.0.0 dev eth0  2>/dev/null > /dev/null
	if test -f /etc/opendomo/dhcpd.conf; then
		echo -n "Starting network (as DHCP server) ..."
		touch /var/log/dhcp.leases
		chmod 660 /var/log/dhcp.leases
		/sbin/ifconfig eth0 192.168.2.2
		if test -x /usr/sbin/udhcpd; then
			/usr/sbin/udhcpd -S /etc/opendomo/dhcpd.conf > /dev/null
		else
			echo -n " UDHCPD missing!"
			exit 1
		fi
	else
		if test -f /etc/opendomo/resolv.conf; then
			cp /etc/opendomo/resolv.conf /etc/
		fi
		if test -f /etc/opendomo/network.conf; then
			IPADDRESS=`grep IPADDRESS $CFGGILE | cut -f2 -d=`
			DEFAULTGW=`grep DEFAULTGW $CFGGILE | cut -f2 -d=`
			NTPSERVER=`grep NTPSERVER $CFGGILE | cut -f2 -d=`
			DNSSERVER=`grep DNSSERVER $CFGGILE | cut -f2 -d=`
			/sbin/ifconfig eth0 $IPADDRESS
			echo -n "Starting network (using $IPADDRESS - $DEFAULTGW)..."
			test -z "$DEFAULTGW" || /sbin/route add default gw $DEFAULTGW eth0
		else
			echo -n "Starting network (looking for a DHCP server)..."
			if udhcpc $OPTNOW >> /var/log/udhcp.log 2>/dev/null
			then
				#TODO Display IP
				echo -n "IP obtained!"
			else
				exit 1
			fi
		fi
	fi
	# Adding an auto-configuration IP for easy access
	if ping 169.254.0.25 >/dev/null
	then
		ifconfig eth0:1 169.254.0.26	
	else
		ifconfig eth0:1 169.254.0.25
	fi
	# Setting a unique hostname:
	HN="/etc/opendomo/hostname"
	if ! test -f $HN; then
		ifconfig | grep eth0 | cut -b39- | \
			sed -e 's/://g' -e 's/^/od/' > $HN
	fi
	chown admin /etc/opendomo/hostname
	hostname `cat $HN` > /dev/null
	# Once the network is started we try to synchronize with the NTP host
	if test -n "$NTPSERVER" &&  test -x /usr/bin/ntpdate; then
		/usr/bin/ntpdate $NTPSERVER 2>/dev/null
	fi
	if test -n "$DNSSERVER"; then
		echo "nameserver $DNSSERVER" >> /etc/resolv.conf
	fi
}

stop(){
	echo -n "Stopping network ..."
	killall udhcpc 2> /dev/null
	killall udhcpd 2> /dev/null
}

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart|reload)
  	stop
  	start
	;;
  *)
	echo $"Usage: $0 {start|stop|restart}"
	exit 1
esac
exit 0
